#include "GLShader.h"
#include "Util.h"
#include <fstream>
#include <sstream>

using namespace std;

GLShader::GLShader(GLenum shaderType, const std::string& file)
{
	compiled = false;
	fileName = getFileName(file);
	basePath = getBasePath(file);

	if (fileExists(file))
	{
		readFile(file, &code);

		name = glCreateShader(shaderType);
	}
	else
	{
		fprintf(stderr, "Shader file %s not found!", file.c_str());
	}
}

GLShader::~GLShader()
{
	glDeleteShader(name);
}

bool GLShader::compile()
{
	const char* ccode = code.c_str();
	GLint codeLength = code.length();
	glShaderSource(name, 1, &ccode, &codeLength);

	glCompileShader(name);
	GLint status;
	glGetShaderiv(name, GL_COMPILE_STATUS, &status);

	GLint length;
	glGetShaderiv(name, GL_INFO_LOG_LENGTH, &length);
	compiled = true;
	if (length > 1)
	{
		char* log = new char[length];
		glGetShaderInfoLog(name, length, NULL, log);
		if (string(log).find("No errors.") == string::npos)
		{
			fprintf(stdout, "Shader %s: ", fileName.c_str());
			if (status != GL_TRUE)
			{
				fprintf(stderr, "Compilation failed!\n");
				compiled = false;
			}
			else
				fprintf(stdout, "\n");

			fprintf(stderr, "%s", log);
			delete[] log;
		}
	}

	return compiled;
}